﻿#include "HugeMsgPanel.h"
#include "ui_HugeMsgPanel.h"

#ifdef Q_OS_WIN
#include <Windows.h>
#endif


HugeMsgPanel::HugeMsgPanel(QWidget *parent)
    : FWidget(parent)
    , ui(new Ui::HugeMsgPanel)
    , m_btnTop(new QPushButton(this))
{
    ui->setupUi(this);
    setWindowTitle("ShowMsg");
    setAttribute(Qt::WA_DeleteOnClose, false); // 关键设置

    updateTopIcon(false);
    connect(m_btnTop, &QPushButton::clicked, this, &HugeMsgPanel::onBtnTopClicked);
    titleBar()->addStandardButton(m_btnTop);

    resize(640, 480);

    m_btnTop->click();
}

HugeMsgPanel::~HugeMsgPanel()
{
    delete ui;
}

HugeMsgPanel *HugeMsgPanel::showMsg(const QString &msg, int fontsize)
{
    static HugeMsgPanel* wgt = nullptr;
    if (!wgt) {
        wgt = new HugeMsgPanel();
    }
    // 会改变样式，不可取
    // wgt->ui->teMsg->setStyleSheet(QString("font-size: %1px;").arg(fontsize));

    // 字体不生效，不可取
    // QFont font = wgt->ui->teMsg->font();
    // font.setPixelSize(fontsize);
    // wgt->ui->teMsg->setFont(font);

    QTextCursor cursor = wgt->ui->teMsg->textCursor();
    cursor.select(QTextCursor::Document);
    QTextCharFormat fmt;
    fmt.setProperty(QTextFormat::FontPixelSize, QVariant(fontsize)); // 像素大小
    cursor.mergeCharFormat(fmt);
    wgt->ui->teMsg->setTextCursor(cursor);

    wgt->ui->teMsg->setPlainText(msg);

    wgt->show();

    return wgt;
}

void HugeMsgPanel::onBtnTopClicked()
{
    // 修复 windows 切换置顶状态下窗口闪烁的问题
#ifdef Q_OS_WIN
    HWND hwnd = reinterpret_cast<HWND>(winId());
    LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
    bool isTop = ((exStyle & WS_EX_TOPMOST) != 0);
    SetWindowPos(hwnd,
                 isTop ? HWND_NOTOPMOST : HWND_TOPMOST,
                 0, 0, 0, 0,
                 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
#else
    bool isTop = windowFlags().testFlag(Qt::WindowStaysOnTopHint);
    setWindowFlag(Qt::WindowStaysOnTopHint, !isTop);
    show();
#endif
    updateTopIcon(!isTop);
}

void HugeMsgPanel::updateTopIcon(bool isTop)
{
    m_btnTop->setIcon(QIcon(isTop ? ":/imgs/pin_fill.png" : ":/imgs/pin.png"));
}
